<?php

/**
 * ExtHelper class file
 *
 * @author TrueSoftware B.V. (The Netherlands)
 * @link http://www.ext4yii.com
 * @copyright Copyright 2007-2010 TrueSoftwareB.V. all rights reserved.
 * @license http://www.ext4yii.com/license/
 *          EVALUATION VERSION - NOT FOR COMMERCIAL USE OR DISTRIBUTION.
 * @version 0.7.2
 */
defined('HTML_VALUE_SIG') or define('HTML_VALUE_SIG', '_$ixh');
defined('JAVASCRIPT_VALUE_SIG') or define('JAVASCRIPT_VALUE_SIG', '_$ixj');

/**
 * ExtHelper contains various helper methods in order to help you develop
 * custom Ext4Yii templates and controllers. ExtHelper should not be Instantiated
 * hence all of the available methods are static.
 */
class ExtHelper
{
    /**
     * @view
     * <p>createTreeNode is a helper method for creating static ExtTreePlanel nodes.</p>
     * <p>For example:</p>
     * <ext:Code brush="php">
     * $nodes = array(
     *     ExtHelper::createTreeNode(1, 'My App', 'IconApplication',
     *          array('mydata' => 'myvalue'), array(
     *              ExtHelper::createTreeNode(2, 'My Module', 'IconCog',
     *                  array('moduleid' => 'someid'))
     *     ))
     * );
     * </ext:Code>
     * <ext:Code>
     * <ext:TreePanel title="MyTree">
     *     <prop:Root>
     *         <ext:TreeNode text="root">
     *             <prop:Nodes>
     *                 <?php echo implode("\r\n",$nodes);?>
     *             </prop:Nodes>
     *         </ext:TreeNode>
     *     </prop:Root>
     * </ext:TreePanel>
     * </ext:Code>
     * @param mixed $id is the node itentifier.
     * @param string $text is the node caption.
     * @param string $icon is an iconCls, defaukts to null.
     * @param array $options is an key=>value array which renders to additional node attributes.
     * @param array $nodes is an array of nodes to be placed ar this nodes children.
     * @return string a string to be printed in the template
     */
    public static function createTreeNode($id, $text, $icon=null, $options=array(), $nodes=array())
    {
        $tpl = array();
        $icon = is_null($icon) ? '' : 'iconcls="' . $icon . '"';
        $tpl[] = '<ext:TreeNode id="' . $id . '" text="' . $text . '" ' . $icon . '>';
        if (is_array($nodes) && count($nodes) != 0)
        {
            $tpl[] = '<prop:Nodes>';
            foreach ($nodes as $node)
                $tpl[] = $node;
            $tpl[] = '</prop:Nodes>';
        }
        if (is_array($options) && count($options) != 0)
        {
            $tpl[] = "<prop:Configs>";
            foreach ($options as $key => $value)
            {
                $tpl[] = '<ext:ConfigItem  name="' . $key . '" value="' . $value . '"/>';
            }
            $tpl[] = "</prop:Configs>";
        }
        $tpl[] = '</ext:TreeNode>';
        return implode("\r\n", $tpl);
    }

    /**
     * @view
     * <p>The FormResult can be used to create a valid response value for form
     * submissions. This function generates a JSON object which is consumed after
     * *form*.submit(...) is performed.</p>
     * <ext:Code brush="php">
     * <?php
     *      public function actionSaveAccount()
     *      {
     *          if($this->database->save($_POST))
     *          {
     *              echo ExtHelper::FormResult(true);
     *          }
     *          else
     *          {
     *              echo ExtHelper::FormResult(false,
     *                  array('myMsg'=>'save failed'));
     *          }
     *      }
     * ?>
     * </ext:Code>
     * @param boolean $success Provide true when the form submission is handled successfully,<br/>otherwise return false.
     * @param array $data is an array which can contain additional info for further<br/>client-side procesing.
     * @return string that is a JSON string object
     */
    public static function FormResult($success, $data=null)
    {
        if (!is_bool($success))
            $success = false;

        if (is_null($data))
            $data = array();

        $data['success'] = $success;

        return CJSON::encode($data);
    }

    /**
     * @view
     * <p>This function formats a string based on key placeholders. Each key
     * placeholder must start with a '@' character. The provided data must
     * an associative array having keys map to each key placeholder.
     * </p>
     * <p>Usage:</p>
     * <ext:Code brush="php">ExtHelper:ToString('Hello @name',array('name','John');</ext:Code>
     * @param string $message is a string template containing key placeholders.
     * @param array $data is an associative containing key=>value records.
     * @return string the formatted string.
     */
    public static function ToString($message, $data)
    {
        foreach ($data as $key => $value)
            $message = str_replace("@$key", $value, $message);
        return $message;
    }

    /**
     * This function is used the retuen a p.a.k.e.d version of the input $script
     * @param string $script the input JavaScript
     * @return string p.a.k.e.d JavaScript
     */
    public static function packScript($script)
    {
        if (Yii::app()->ext4yii->disable_pack === true)
            return $script;
        else
        {
            $packer = new ExtJavaScriptPacker($script, 'Normal', true, false);
            return $packer->pack();
        }
    }

    private static function is_assoc_array($php_val)
    {
        if (!is_array($php_val))
        {
            # Neither an associative, nor non-associative array.
            return false;
        }

        $given_keys = array_keys($php_val);
        $non_assoc_keys = range(0, count($php_val));

        if (function_exists('array_diff_assoc'))
        { # PHP > 4.3.0
            if (array_diff_assoc($given_keys, $non_assoc_keys))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            if (array_diff($given_keys, $non_assoc_keys) and array_diff($non_assoc_keys, $given_keys))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

}

?>
